/*
 * @Description:
 * @Author: zhihong deng
 * @Date: 2021-08-17 21:37:02
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-09-28 22:32:37
 */
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/components/Home.vue'
import storage from '../utils/storage'
import API from '../api'
import util from '../utils/utils'

const routes = [
	{
		name: 'home',
		path: '/',
		meta: {
			title: '首页',
		},
		component: Home,
		redirect: '/welcome', //重定向到哪个页面
		children: [
			{
				name: 'welcome',
				path: '/welcome',
				meta: {
					title: '欢迎页',
				},
				component: () => import('@/views/Welcome.vue'), // ES6按需引入语法
			},
			// {
			// 	name: 'user',
			// 	path: 'system/user',
			// 	meta: {
			// 		title: '用户管理',
			// 	},
			// 	component: () => import('@/views/User.vue'),
			// },
			// {
			// 	name: 'menu',
			// 	path: 'system/menu',
			// 	meta: {
			// 		title: '菜单管理',
			// 	},
			// 	component: () => import('@/views/Menu.vue'),
			// },
      // {
			// 	name: 'role',
			// 	path: 'system/role',
			// 	meta: {
			// 		title: '角色管理',
			// 	},
			// 	component: () => import('@/views/Role.vue'),
			// },
      // {
			// 	name: 'dept',
			// 	path: 'system/dept',
			// 	meta: {
			// 		title: '部门管理',
			// 	},
			// 	component: () => import('@/views/Dept.vue'),
			// },
      // {
			// 	name: 'audit',
			// 	path: '/audit/leave',
			// 	meta: {
			// 		title: '休假管理',
			// 	},
			// 	component: () => import('@/views/Leave.vue'),
			// },
		],
	},
	{
		name: 'login',
		path: '/login',
		meta: {
			title: '登录',
		},
		component: () => import('@/views/Login.vue'),
	},
  {
		name: '404',
		path: '/404',
		meta: {
			title: '页面不存在',
		},
		component: () => import('@/views/404.vue'),
	},
]
const router = createRouter({
	history: createWebHashHistory(),
	routes,
})
// 异步加载路由
async function loadAsyncRoutes () {
  let userInfo = storage.getItem('userInfo') || {}
  // 如果有token，就获取到权限列表
  if (userInfo.token) {
    try {
      const { menuList } = await API.getPermissionList()
      let routes = util.generateRoute(menuList)
      // 遍历路由，批量添加路由
      routes.map(route => {
        let url = `../views/${route.component}.vue`
        route.component = () => import(url);
        router.addRoute("home", route);// 动态添加到home的子路由中
      })
    } catch (error) {
      
    }
  }
}
await loadAsyncRoutes()


// 判断当前地址是否可以访问
// function checkPermission (path) {
//   let hasPermission = router.getRoutes().filter(route => route.path == path).length
//   if(hasPermission){
//     return true
//   }else{
//     return false
//   }
// }
// 导航守卫
router.beforeEach((to, from, next) => {
  // if(checkPermission(to.path)){
    if(router.hasRoute(to.name)) {
    // 给选中的路由显示标题在头部
    document.title = to.meta.title
    next()
  }else{
    next('/404')
  }
})
export default router
